package com.wolf.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wolf.common.exception.NoStockException;
import com.wolf.common.to.SkuHasStockTo;
import com.wolf.common.to.mq.OrderTo;
import com.wolf.common.to.mq.StockDetailTo;
import com.wolf.common.to.mq.StockLockedTo;
import com.wolf.common.utils.PageUtils;
import com.wolf.common.utils.Query;
import com.wolf.common.utils.R;
import com.wolf.gulimall.ware.dao.WareSkuDao;
import com.wolf.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.wolf.gulimall.ware.entity.WareOrderTaskEntity;
import com.wolf.gulimall.ware.entity.WareSkuEntity;
import com.wolf.gulimall.ware.feign.OrderFeignService;
import com.wolf.gulimall.ware.feign.ProductFeignService;
import com.wolf.gulimall.ware.service.WareOrderTaskDetailService;
import com.wolf.gulimall.ware.service.WareOrderTaskService;
import com.wolf.gulimall.ware.service.WareSkuService;
import com.wolf.gulimall.ware.vo.OrderItemVo;
import com.wolf.gulimall.ware.vo.OrderVo;
import com.wolf.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {


    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId) && !"0".equalsIgnoreCase(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId) && !"0".equalsIgnoreCase(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 将成功采购的商品进行入库
     *
     * @param skuId  skuID
     * @param wareId 仓库ID
     * @param skuNum 入库数量
     */
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //先判断仓库里面有没有这个商品
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            //没有商品,就添加一条数据
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //调feign查询sku名称信息
            try {
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0) {
                    Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
                log.error("e", e);
            }
            wareSkuDao.insert(wareSkuEntity);
        } else {
            //有,更新仓库数据
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

    /**
     * 根据商品ID,判断是否有库存
     *
     * @param skuIds 商品ID结合
     * @return 库存数据集合
     */
    @Override
    public List<SkuHasStockTo> getSkuHasStock(List<Long> skuIds) {
        return skuIds.stream().map(skuId -> {
            SkuHasStockTo skuHasStockVo = new SkuHasStockTo();
            Long count = baseMapper.getHasStock(skuId);
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count != null && count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());

    }


    /**
     * 为某个订单锁定库存
     * 默认运行时异常都会回滚
     * 库存需要解锁的场景:
     * 1. 下订单成功,超时未支付被系统自动取消,或者用户手动取消订单
     * 2.下订单成功,库存锁定成功,其他业务执行异常,导致订单事务回滚,库存事务也需要进行回滚,即库存解锁
     *
     * @param wareSkuInfoVo 订单信息
     * @return 库存锁定结果
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo wareSkuInfoVo) {
        //保存库存工作单详情
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(wareSkuInfoVo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);

        //1.找到每个商品在哪个仓库有库存
        List<OrderItemVo> locks = wareSkuInfoVo.getLocks();
        List<SkuWareHasStock> stocks = locks.stream().map(lock -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = lock.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setNum(lock.getCount());
            //查询商品在哪个仓库有库存
            List<Long> wareIds = baseMapper.listWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareIds(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());
        //2.锁定库存
        for (SkuWareHasStock stock : stocks) {
            boolean stocked = false;//锁定库存标志位
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareIds();
            if (wareIds == null || wareIds.size() == 0) {
                //没有任何仓库存在该商品的库存,抛出异常
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                Long count = baseMapper.lockSkuStock(skuId, wareId, stock.getNum());
                if (count == 1) {
                    stocked = true;//修改标志位为TRUE,代表当前商品在当前仓库锁库存成功
                    //库存锁定成功,保存库存工作单数据信息
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "", stock.getNum(), wareOrderTaskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    //发消息给rabbitmq,如果每一个商品都锁定成功,将当前商品锁定了几件的工作单记录发送给mq
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTo);
                    stockLockedTo.setId(wareOrderTaskEntity.getId());
                    stockLockedTo.setDetail(stockDetailTo);
                    //将订单中库存锁定成功的消息发送到mq延迟队列中
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                }
                //当前仓库锁定失败,重试下一个仓库
            }
            if (!stocked) {
                //当期商品在所有仓库都没有库存可以锁定
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    /**
     * 仓库商品信息关联实体
     */
    @Data
    static class SkuWareHasStock {
        /**
         * 商品skuId
         */
        private Long skuId;

        /**
         * 锁定数量
         */
        private Integer num;

        /**
         * 仓库ID列表
         */
        private List<Long> wareIds;
    }

    /**
     * 解锁库存
     *
     * @param stockLockedTo 工作单数据信息
     */
    @Override
    public void unLockStock(StockLockedTo stockLockedTo) {
        log.info("进入解锁库存方法!!");
        StockDetailTo detail = stockLockedTo.getDetail();
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(stockLockedTo.getDetail().getId());
        if (detailEntity != null) {
            //需要进行解锁操作: 没有订单时必须解锁;有订单还要查看订单状态,当订单状态为已取消的时候进行解锁
            WareOrderTaskEntity taskDetailEntity = wareOrderTaskService.getById(stockLockedTo.getId());
            //根据订单编号查询订单状态
            String orderSn = taskDetailEntity.getOrderSn();
            R order = orderFeignService.getOrderStatus(orderSn);
            if (order.getCode() == 0) {
                OrderVo data = order.getData(new TypeReference<OrderVo>() {
                });
                //库存解锁
                if (data == null || data.getStatus() == 4) {
                    //当库存工作单的状态为:已锁定时才能进行解锁操作
                    log.info("库存工作单的状态为:{}",detailEntity.getLockStatus());
                    if (detailEntity.getLockStatus() == 1) {
                        //库存解锁
                        wareSkuDao.unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum());
                        //更新库存工作单状态:已解锁
                        WareOrderTaskDetailEntity taskDetailEntity1 = new WareOrderTaskDetailEntity();
                        taskDetailEntity1.setId(detailEntity.getId());
                        taskDetailEntity1.setLockStatus(2);
                        wareOrderTaskDetailService.updateById(taskDetailEntity1);
                        log.info("库存解锁成功!");
                    }
                }
            } else {
                //需要重新进行解锁
                throw new RuntimeException("远程服务调用失败!");
            }
        }
    }


    /**
     * 订单关闭解锁库存
     * 防止订单服务卡顿,导致订单状态消息一直不能修改,
     * 当库存消息优先到期时,不能获取到订单的最新状态,导致卡顿的订单永远不能解锁库存
     *
     * @param order 订单信息
     */
    @Transactional
    @Override
    public void unLockStock(OrderTo order) {
        log.info("进入订单关闭解锁库存方法!");
        String orderSn = order.getOrderSn();
        //查询最新的库存状态,防止重复解锁库存
        WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        //根据库存工作单查询所有未解锁库存进行解锁
        List<WareOrderTaskDetailEntity> detailEntities = wareOrderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id", wareOrderTaskEntity.getId())
                        .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity detailEntity : detailEntities) {
            wareSkuDao.unLockStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum());
        }
    }


}